package com.wd.live.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.wd.live.model.SpUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Description : BaseFragment
 *
 * @author 邵玺博
 * @date 2022/11/03
 */
public abstract class BaseFragment <VM extends BaseViewModel,DB extends ViewDataBinding> extends Fragment implements Observer {
    public VM viewmodel;
    public DB databind;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //设置布局
        SpUtils.init(getActivity());
        if(databind==null){
            databind= DataBindingUtil.inflate(inflater,initLayout(),container,false);
            databind.setLifecycleOwner(this);
        }
        //判断为空调用方法
        if(viewmodel==null){
            initViewModel();
        }
        initData();
        return databind.getRoot();
    }

    protected abstract void initData();

    private void initViewModel() {
        //判断为空赋值
        if(viewmodel==null){
            Class clazz=null;
            Type type = getClass().getGenericSuperclass();
            if(type instanceof ParameterizedType){
                clazz=(Class) ((ParameterizedType)type).getActualTypeArguments()[0];
            }else{
                clazz=getClass();
            }
            viewmodel=(VM) ViewModelProviders.of(this).get(clazz);
        }
    }

    protected abstract int initLayout();
}
